package com.bolun998300.personal_blog_springboot.controller.background;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.bolun998300.personal_blog_springboot.Utils.DateUtil;
import com.bolun998300.personal_blog_springboot.Utils.Result;
import com.bolun998300.personal_blog_springboot.Utils.WangEditor;
import com.bolun998300.personal_blog_springboot.Utils.WebFileUtil;
import com.bolun998300.personal_blog_springboot.pojo.Blog;
import com.bolun998300.personal_blog_springboot.pojo.Blog_Tag;
import com.bolun998300.personal_blog_springboot.pojo.Blogger;
import com.bolun998300.personal_blog_springboot.pojo.Tag;
import com.bolun998300.personal_blog_springboot.service.BlogService;
import com.bolun998300.personal_blog_springboot.service.BlogTypeService;
import com.bolun998300.personal_blog_springboot.service.Blog_TagService;
import com.bolun998300.personal_blog_springboot.service.TagService;

@RestController
public class BlogController {

    @Autowired
    private BlogService blogService;
    @Autowired
    private BlogTypeService blogTypeService;
    @Autowired
    private TagService tagService;
    @Autowired
    private Blog_TagService blogTagService;
    
    /**
     * 获取所有博客
     * @return
     */
    @GetMapping(value = "/blogs")
    public List<Blog> getBlogList(){
        List<Blog> list = blogService.list();
        for(Blog bean : list){
            bean.setTypeName(blogTypeService.get(bean.getTypeId()).getTypeName());
        }
        return blogService.list();
    }
    
    /**
     * 获取所有置顶博客
     * @return
     */
    @GetMapping(value = "/blogsTop")
    public List<Blog> getBlogListByTop(){
        List<Blog> list = blogService.findByIsDeleteAndNewsTopOrderByCreateTimeDesc();
        for(Blog bean : list){
            bean.setTypeName(blogTypeService.get(bean.getTypeId()).getTypeName());
            List<Blog_Tag> blogTagList = blogTagService.findByBlogId(bean.getId());
            List<Tag> tagList = new ArrayList<>();
            for(Blog_Tag blogTag : blogTagList) {
            	Tag tag = tagService.getById(blogTag.getTagId());
            	tagList.add(tag);
            }
            bean.setTagList(tagList);
        }
        return list;
    }
    
    /**
     * 分页获取列表
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "/blogs/listByPage")
    public HashMap<String,Object>  getBlogByPage(int page ,int  limit){
        Page<Blog> pageFromJPA = blogService.listByPage(page,limit,false);
        return returnPage(pageFromJPA);
    }
    
    
    @GetMapping(value = "/blogs/getBlogByPageDeleted")
    public HashMap<String,Object> getBlogByPageDeleted(int page,int limit){
    	Page<Blog> pageFromJPA = blogService.listByPage(page,limit,true);
        return returnPage(pageFromJPA);
    }

    @GetMapping("/blogs/getDraftBlogByPage")
    public HashMap<String,Object> getDraftBlogByPage(int page,int limit){
        Page<Blog> pageFromJPA = blogService.getDraftBlogByPage(page,limit);
        return returnPage(pageFromJPA);
    }
    
    
    
    

    /**
     * 搜索
     * @param page
     * @param limit
     * @param key
     * @return
     */
    @GetMapping(value = "/blogs/searchByName")
    public HashMap<String,Object> searchByName(int page,int limit,String key){
        Page<Blog> pageFromJpa = blogService.searchByName(page,limit,key);
        return returnPage(pageFromJpa);
    }

    /**
     * 分页查询列表非置顶
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "/blogs/listByPageNoTop")
    public HashMap<String,Object>  getBlogByPageNoTop(int page ,int  limit){
        Page<Blog> pageFromJPA = blogService.listByPageNoTop(page,limit);
        
        return returnPage(pageFromJPA);
    }


    @GetMapping("/blogs/{id}")
    public Blog get(@PathVariable int id){
    	Blog bean = blogService.get(id);
    	bean.setClickHit(bean.getClickHit()+1);
    	blogService.update(bean);
		bean.setTypeName(blogTypeService.get(bean.getTypeId()).getTypeName());
        return bean;
    }
    
    /**
     * 列表操作 删除和置顶
     * @param id
     * @param operate
     * @return
     */
    @PutMapping("/blogs/{id}/{operate}")
    public Object update(@PathVariable("id") int id,@PathVariable("operate") String operate){
        Blog blog = blogService.get(id);
        if(operate.equals("top")){
            blog.setNewsTop(!blog.isNewsTop());
        }else if(operate.equals("delete")){
            blog.setDelete(true);
        }
        blogService.update(blog);
        return Result.success();
    }
    
    /**
     * 彻底删除
     * @param id
     * @return
     */
    @DeleteMapping("/blogs/{id}")
    public Object delete(@PathVariable("id") int id) {
    	blogService.delete(id);
    	return Result.success();
    }
    
    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping("/blogs/deleteAll")
    public Object deleteAll(int[] ids) {
    	for(int i = 0;i<ids.length ;i++){
            blogService.delete(ids[i]);
        }
        return Result.success();
    }
    
    /**
     * 批量还原文章
     * @param
     * @return
     */
    @PutMapping("/blogs/backAll")
    public Object backBlogs(HttpServletRequest request) {
    	String[] ids = request.getParameterValues("ids");
        for(int i = 0;i<ids.length ;i++){
            int id = Integer.parseInt(ids[i]);
            Blog blog = blogService.get(id);
            blog.setDelete(false);
            blogService.update(blog);
        }
        return Result.success();
    }
    
    
    /**
     * 还原文章
     * @param id
     * @return
     */
    @PutMapping("/blogs/back/{id}")
    public Object backBlog(@PathVariable("id") int id) {
    	Blog blog = blogService.get(id);
    	blog.setDelete(false);
    	blogService.update(blog);
    	return Result.success();
    }
    
    
    
    
    /**
     * 批量放进回收站
     * @param request
     * @return
     */
    @PutMapping(value = "/blogs/putInRecycle")
    public Object putInRecycle(HttpServletRequest request){
        String[] ids = request.getParameterValues("ids");
        for(int i = 0;i<ids.length ;i++){
            int id = Integer.parseInt(ids[i]);
            Blog blog = blogService.get(id);
            blog.setDelete(true);
            blogService.update(blog);
        }
        return Result.success();
    }

    /**
     * 新增博客
     * @param blog
     * @return
     */
    @PostMapping("/blogs")
    public Object add(@RequestBody Blog blog){
        Subject subject = SecurityUtils.getSubject();
        Blogger blogger = (Blogger)subject.getSession().getAttribute("user");
        blog.setNewsAuthor(blogger.getNickName());
        blog.setReleaseDate(new Date());
        blog.setCreateTime(new Date());
        blogService.save(blog);
        
        String tags = blog.getKeyWord();
        String[] tagArr=tags.split(" ");
        for(String tag : tagArr) {
        	Tag bean = tagService.get(tag);
        	if(null == bean) {
        		bean = new Tag();
        		bean.setTagName(tag);
        		bean.setTagCreateDate(new Date());
        		tagService.add(bean);
        	}
        	Blog_Tag blogTag = new Blog_Tag();
        	blogTag.setTagId(bean.getId());
        	blogTag.setBlogId(blog.getId());
        	blogTagService.add(blogTag);
        }
        return Result.success();
    }
    
    /**
     * 修改博客
     * @param blog
     * @return
     */
    @PutMapping("/blogs")
    public Object update(@RequestBody Blog blog){
        blog.setUpdateTime(new Date());
        blogService.update(blog); 
        return Result.success();
    }



    @GetMapping("/blogs/listByPageAndSearchWord")
    public HashMap<String,Object> getBlogByPageAndSearchWord(int page,int limit,String searchWord){
        Page<Blog> pageFromJpa = blogService.getBlogByPageAndSearchWord(page,limit,searchWord);

        return returnPage(pageFromJpa);
    }





    @GetMapping(value = "/blogs/listByPageAndTypeId")
    public HashMap<String,Object>  getBlogByPageAndTypeId(int page ,int  limit,int typeId){
        Page<Blog> pageFromJPA = blogService.listByPageAndTypeID(page,limit,typeId);
        return returnPage(pageFromJPA);
    }
    
    @GetMapping(value = "/blogs/findByIsDeleteOrderByClickHitDesc")
    public List<Blog> findByIsDeleteOrderByClickHitDesc(){
    	Page<Blog> pageFromJPA = blogService.findByIsDeleteOrderByClickHitDesc();
    	return pageFromJPA.getContent();
    }

    @GetMapping("/blogs/listByPageAndTagId")
    public HashMap<String,Object> listByPageAndTagId(int page ,int  limit,int tagId){
    	Page<Blog> pageFromJPA = blogService.listByPageAndTagId(page,limit,tagId);
    	return returnPage(pageFromJPA);
    }

    
    @PostMapping(value="/blogs/uploadBlogFaceImg")
    public Object uploadBlogFaceImg( MultipartFile faceImg,
            HttpServletRequest request) {
    	OutputStream os = null;
        InputStream is = null;
        try {
        	String fileName = faceImg.getOriginalFilename();
            String fileType = fileName.split("\\.")[1];
            String filePath=WebFileUtil.getSystemRootPath(request);
            String newFileName = "blogFaceImg"+DateUtil.getCurrentDateStr()+"."+fileType;
            
            String date = DateUtil.formatDate(new Date(),"yyyy-MM-dd");
            String newFolder="/uploadImage/blogFaceImg/"+date+"/";
            String newFilePath=filePath+newFolder;
            WebFileUtil.createFold(new File(newFilePath));
            
            os = new FileOutputStream(newFilePath+newFileName);
            is = faceImg.getInputStream();
            IOUtils.copy(is, os);
            String url = request.getScheme() + "://" + request.getServerName()
            + ":" + request.getServerPort() +"/personal_blog"+ newFolder + newFileName;
            HashMap<String,Object> map = new HashMap<String,Object>();
            map.put("code", 0);
            map.put("msg", "");
            	Map<String,Object> map1 = new HashMap<String,Object>();
            	map1.put("src", url);
            map.put("data", map1);
            return map;
        }catch (Exception e) {
		}finally {
            try {
				is.close();
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
		return null;
    }
    
    public HashMap<String,Object> returnPage(Page<Blog> pageFromJPA){
    	HashMap<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",pageFromJPA.getTotalElements());
        List<Blog> list =pageFromJPA.getContent();
        for(Blog bean : list){
            bean.setTypeName(blogTypeService.get(bean.getTypeId()).getTypeName());
            List<Blog_Tag> blogTagList = blogTagService.findByBlogId(bean.getId());
            List<Tag> tagList = new ArrayList<>();
            for(Blog_Tag blogTag : blogTagList) {
            	Tag tag = tagService.getById(blogTag.getTagId());
            	tagList.add(tag);
            }
            bean.setTagList(tagList);
        }
        map.put("data",pageFromJPA.getContent());
        map.put("pages",pageFromJPA.getTotalPages());
    	return map;
    }
    
    
    
    






    //图片上传
    @RequestMapping(value = "/upload",method=RequestMethod.POST)
    @ResponseBody
    public WangEditor uploadFile(
            @RequestParam("myFile") MultipartFile multipartFile,
            HttpServletRequest request) throws IOException {
        OutputStream os = null;
        InputStream is = null;

        try {
            String fileName = multipartFile.getOriginalFilename();
            String fileType = fileName.split("\\.")[1];
            String filePath=WebFileUtil.getSystemRootPath(request);
            String newFileName = DateUtil.getCurrentDateStr()+"."+fileType;

            String date = DateUtil.formatDate(new Date(),"yyyy-MM-dd");
            String newFolder="/uploadImage/blogImg/"+date+"/";
            String newFilePath=filePath+newFolder;
            WebFileUtil.createFold(new File(newFilePath));


            os = new FileOutputStream(newFilePath+newFileName);
            is = multipartFile.getInputStream();
            IOUtils.copy(is, os);

//            // 获取项目路径
//            String realPath = request.getSession().getServletContext()
//                    .getRealPath("");
//            InputStream inputStream = multipartFile.getInputStream();
//            String contextPath = request.getContextPath();
//            // 服务器根目录的路径
//            String path = realPath.replace(contextPath.substring(1), "");
//            // 根目录下新建文件夹upload，存放上传图片
//            String uploadPath = path + "upload";
//            // 获取文件名称
//            String filename = multipartFile.getOriginalFilename();
//           // String filename = MoteUtils.getFileName();
//            // 将文件上传的服务器根目录下的upload文件夹
//            File file = new File(uploadPath, filename);
//            FileUtils.copyInputStreamToFile(inputStream, file);
            // 返回图片访问路径
            String url = request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort() +"/personal_blog"+ newFolder + newFileName;

            String [] str = {url};
            WangEditor we = new WangEditor(str);
            return we;
        } catch (Exception e) {
        }finally {
            is.close();
            os.close();
        }
        return null;

    }




}
